local filename = "propexchange.lua"

local timetool = require "timetool"
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local filelog =require "filelog"
local redisdao = require "redisdao"
require "pubenum"

local json = require "cjson"
json.encode_sparse_array(true,1,1)

local service = nil
local CMD = {
	service = nil
}

--道具类型
local PROP_TYPE = {
    FANGKA = 1,         --房卡
    DIAMOND = 2,        --金豆
    COIN = 3,           --金币
}

--
--更新背包道具
--prop_id 道具id
--num 道具数量
--
local function update_knapsack(rid, prop_id, num)
    --获得道具配置
    local curitem = skynet.call(".knapsack", "lua", "getpropconf", prop_id)
    if not curitem then
        return
    end

    local updateitem = { id = prop_id}
    local kid = math.floor(prop_id / 100)
    if kid == PropKind.HEADFRAME then   --头像框,增加有效时间
        updateitem.value = num * curitem.effecttime * 24 * 3600
        updateitem.state = 2    --购买后不装备
    elseif kid == PropKind.INTERPROP or kid == PropKind.VIPCARD then    --会员卡 互动表情，增加数量
        updateitem.value = num
    else
        return
    end

    --更新
    skynet.call(".knapsack", "lua", "updateknapsack", rid, {[1] = updateitem})
    local status, propitem = skynet.pcall(skynet.call, ".knapsack", "lua", "getpropbyid", rid, prop_id)
    if not propitem then
        return nil
    end
    return propitem
end

--
--获得兑换商品id
--
local function get_goodsid(exchange_list, msgbody)
    local prop_type = msgbody.prop_type or 0
    local number = msgbody.number or 0
    local target = msgbody.target or 0

    if prop_type <= 0 or number <= 0 or target <= 0 then
        return 0
    end

    for id,item in pairs(exchange_list) do
        if item.src_id == prop_type 
        and item.cost_num == number 
        and item.dest_id == target then
            return id
        end
    end
    
    return 0
end

--
--道具兑换
--
function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end
    msgbody = msgbody or {}

    local begincoin = service.money.coin or 0
    local cur_prop_num = 0
    local target = msgbody.goods_id or 0
    local propname = ""
    local itemvalues = { }
    local response = { }

    --获得兑换表
    local result, data = redisdao.query_data(".gmmqredis", "get", "prop_exchange_list")
    local exchange_list = nil
    if not result or not data then
        return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "兑换失败"}
    else
        exchange_list = json.decode(data) or {}
    end

    --获得兑换道具项
    if target <= 0 then
        target = get_goodsid(exchange_list, msgbody)
    end
    local exchange_item = exchange_list[target] or exchange_list[tostring(target)]
    if not exchange_item then
        return {retcode = EErrCode.ERR_INVALID_PARAMS,retstr = "无效的参数"}  
    end

    --只能用房卡或金豆或金币进行兑换
    local prop_type = exchange_item.src_id or 0
    if prop_type == PROP_TYPE.FANGKA then
        cur_prop_num = service.money.fangka or 0
        propname = "fangka"
    elseif prop_type == PROP_TYPE.DIAMOND then
        cur_prop_num = service.money.diamond or 0
        propname = "diamond"
    elseif prop_type == PROP_TYPE.COIN then
        cur_prop_num = service.money.coin or 0
        propname = "coin"
    else
        return {retcode = EErrCode.ERR_INVALID_PARAMS,retstr = "无效的道具类型"}
    end

    --检测兑换数量
    local number = tonumber(exchange_item.cost_num) or 0
    if number <= 0 or number > cur_prop_num then
        return {retcode = EErrCode.ERR_INVALID_PARAMS,retstr = "金豆数量不足"}
    else
        itemvalues[propname] = -number
    end

    --设置兑换结果
    response.target = exchange_item.dest_id
    response.number = exchange_item.gain_num
    response.goods_id = target

    --修改数据
    if response.target == PROP_TYPE.COIN then    --金豆兑换
        itemvalues.coin = response.number
    end

    local setargs = service:change_money(itemvalues)
	if setargs then
        --记录日志
        local logstr = nil

        local comment = { }
        local now = timetool.get_time()
        comment.tradeid = skynet.call(".nodeuuid", "lua", "getuuid")
        comment.table_uuid = "exchnode" .. "_" .. 0 .. "_" .. 0 .. "_" .. now
        if prop_type == PROP_TYPE.FANGKA then
            logstr = string.format("%d,%d,%s,%d,%d,%d", EFangKaChange.EXCHANGEFANGKA, rid, xx, -number, cur_prop_num, service.money.fangka)
            skynet.send(".fangkalog", "lua", "write", logstr)
        elseif prop_type == PROP_TYPE.DIAMOND then
            logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.EXCHANGE, rid, service.info.level, -number, 0, 0, cur_prop_num, service.money.diamond, service.money.lock_diamond, comment.table_uuid, now, comment.tradeid)
            skynet.send(".diamondlog", "lua", "write_file_redis", logstr, rid)
            --在游戏内兑换，通知游戏节点
            if service.gamenode ~= "" then
			    skynet.pcall(cluster.send, service.gamenode, ".router", "rid_change_diamond", rid, cur_prop_num, -number, service.money.diamond)
		    end	
        end
        if response.target == PROP_TYPE.COIN then
            logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", ECoinChange.EXCHANGE, rid, service.info.level, number, 0, 0, begincoin, service.money.coin, service.money.lock_coin, comment.table_uuid, now, comment.tradeid)
            skynet.send(".coinlog", "lua", "write", logstr)

            --在游戏内兑换，通知游戏节点
            if service.gamenode ~= "" then
			    skynet.pcall(cluster.send, service.gamenode, ".router", "rid_change_coin", rid, begincoin, number, service.money.coin)
		    end	
        end

        --不是金豆兑换时，更新背包
        if response.target > PROP_TYPE.COIN then
            local updateprop = update_knapsack(rid, response.target, response.number)
            local updatelist = {}
            table.insert( updatelist, updateprop)
            --通知玩家,背包信息改变
            local change_notice = { change_prop_listjson = json.encode(updatelist) }
            service:notify_client("changepropN", change_notice)
        end

        return response
    end
	
	return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "兑换失败"}
end

return CMD